<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{this.$router.currentRoute.name}}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-page-header @back="goBack" :content="this.$router.currentRoute.name.substring(this.$router.currentRoute.name.indexOf('/')+1)">
      </el-page-header>
      <!-- 系统通知列表卡片区 -->
      <el-form :inline="true" ref="form"  size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
        </el-row>
        <el-form-item >
          <el-input
              style="width: 140px;"
              clearable
              placeholder="请输入客户名称"
              v-model="queryMap.clientName"
          ></el-input>
        </el-form-item>
        <el-form-item >
          <el-input
              style="width: 140px;"
              clearable
              placeholder="请输入客户电话"
              v-model="queryMap.clientPhone"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              style="width: 140px;"
              placeholder="请选择账号"
              v-model="queryMap.accountName"
              @change="getUserName"
              filterable
          >
            <el-option
                v-for="(name) in accountName"
                :key="name"
                :label="name"
                :value="name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item >
          <el-select v-model="queryMap.userId" style="width: 200px;" filterable placeholder="请选择归属人">
            <el-option
                v-for="(user) in userList"
                :key="user.userId"
                :label="user.userName+'('+user.nickName+')'"
                :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间:">
          <el-date-picker
              type="daterange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions"
              @change="handleDateChange"
              v-model="value2">
          </el-date-picker>
        </el-form-item>
        <el-form-item >
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button type="primary" icon="el-icon-search"  @click="searchBlackList()">查询</el-button>
        </el-form-item>
      </el-form>

      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button style="" icon="el-icon-delete" v-hasPermission="'blacklist:erase'" @click="del">清空黑名单</el-button>
        <el-button style="" icon="el-icon-delete" v-hasPermission="'blacklist:delete'" @click="delBlackList">批量删除</el-button>
        <el-button style="" icon="el-icon-circle-plus-outline"  v-hasPermission="'blacklist:add'" @click="isVisible_add=true">新建</el-button>
        <el-button style="" icon="el-icon-download" @click="downloadTemplate">下载模板</el-button>
        <el-button style="" icon="el-icon-upload" v-hasPermission="'blacklist:import'" @click="isVisible_upload=true">导入黑名单</el-button>
        <el-button @click="downExcel" v-hasPermission="'blacklist:export'" style="" icon="el-icon-download">导出</el-button>

      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable" :data="testData"  size="small"  @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="clientName" label="客户名称" width="200"></el-table-column>
        <el-table-column prop="clientPhone" label="客户电话" width="250"></el-table-column>
        <el-table-column prop="userName" label="创建人" width="150"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="250"></el-table-column>
        <el-table-column prop="remark" label="备注" width="400" ></el-table-column>
        <el-table-column label="操作"  width="135">
          <template v-slot="scope">
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button type="danger"  size="small" icon="el-icon-delete"  v-hasPermission="'blacklist:delete'" plain circle @click="delBlack(scope.row.blacklistId)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>

      <!-- 添加黑名单弹出层 -->
      <div v-if="isVisible_add" class="popups" @click.self="isVisible_add=false">
        <el-main style="width: 27vw;height:  350px">
          <div class="header">
            <h3 style="flex: 1">添加黑名单</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle  @click="isVisible_add=false"></el-button>
            </el-tooltip>
          </div>
          <div style="padding-left: 3vh">
            <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh">
              <el-form-item label="选择账号:">
                <el-select
                    style="width: 240px;"
                    v-model="addForm.accountName"
                >
                  <el-option
                      v-for="(name) in accountName"
                      :key="name"
                      :label="name"
                      :value="name">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户名称:">
                <el-input
                    style="width: 240px;"
                    clearable
                    placeholder="请输入客户名称"
                    v-model="addForm.clientName"
                ></el-input>
              </el-form-item>
              <el-form-item  label="客户电话:">
                <el-input
                    style="width: 240px;"
                    clearable
                    placeholder="请输入客户电话:"
                    v-model="addForm.clientPhone"
                ></el-input>
              </el-form-item>
              <el-form-item  label="备注:"  style="margin-left: 3vh;">
                <el-input
                    style="width: 240px;"
                    clearable
                    placeholder="请输入备注:"
                    v-model="addForm.remark"
                ></el-input>
              </el-form-item>
              <el-form-item style="margin-left: 32.5vh">
                <el-button type="primary" @click="saveBlacklist" :loading="btnLoading" :disabled="btnDisabled">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </div>


      <!-- 上传标签弹出层 -->
      <div v-if="isVisible_upload" class="popups" @click.self="isVisible_upload=false">
        <el-main style="width: 32.5vw;height: 60vh">
          <div class="header">
            <h3 style="flex: 1">添加黑名单</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle  @click="isVisible_upload=false"></el-button>
            </el-tooltip>
          </div>
          <el-form :inline="true" ref="form"  size="small" style="margin-top: 2vh">
            <el-form-item label="选择账号:">
              <el-select
                  style="width: 240px;"
                  v-model="submitForm.accountName"
              >
                <el-option
                    v-for="(name) in accountName"
                    :key="name"
                    :label="name"
                    :value="name">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="padding-left: 7vh;height: 32vh">
            <el-upload
                class="upload-demo"
                :auto-upload="false"
                drag
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="handleError"
                :file-list="fileList"
                multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传xls,xlsx文件，且不超过5M</div>
            </el-upload>
          </div>
          <el-button type="primary" size="medium" @click="submitUpload()" style="margin: 2vh 0 0 43vh;" :loading="btnLoading" :disabled="btnDisabled">确认</el-button>
        </el-main>
      </div>

    </el-card>
  </div>
</template>
<script>
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";
export default {
  components: {ElectUsersBox},
  data() {
    return {
      isVisible_add:false,//添加标签弹出层是否展示
      isVisible_upload :false,//导入标签弹出层是否展示
      btnLoading: false,
      btnDisabled: false,
      activeIndex: '0',//初始显示菜单下标
      total: 0,
      multipleSelection:[],
      accountName:[],//账号
      userList:[],//归属人
      testData: [],//表格信息
      value2: [],//日期选择器
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 10,
        clientName: "",
        clientPhone: "",
        userId: "",
        createTime:null,
        deadline:null,
        isMove:"",
        deptId:"",
        accountName:'',
      },
      addForm: {
        clientName: "",
        clientPhone: "",
        remark:"",
        accountName:'',
      },
      submitForm:{
        accountName:''
      },

      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      // 上传文件列表
      fileList: [],
      excelFile:{},
    };
  },
  methods: {
    // 提交上传
    async submitUpload() {
      console.log(this.excelFile)
      // 验证客户名称是否为空
      if (!this.submitForm.accountName) {
        this.$message({
          type: "error",
          message: "账号没有选择"
        });
        return;
      }
      if (!this.excelFile.name) {
        this.$message({
          type: "error",
          message: "没有导入表格"
        });
        return;
      }
      // 创建 FormData 对象
      const formData = new FormData();
      formData.append("file", this.excelFile.raw);
      formData.append("accountName", this.submitForm.accountName);
      this.btnLoading = true;
      this.btnDisabled = true;
      const { data: res } = await this.$http.post("/system/blacklist/importBlacklist", formData
          ,{
            headers: {
              "Content-Type": "multipart/form-data", // 确保是多部分请求
            },
          });
      if(res.success){
        this.$notify.success({
          title:'操作成功',
          message:'excel文件上传成功',
        });
        //调用查询方法
        await this.getBlackList();
      } else {
        this.isVisible_upload=false;
        return this.$message.error("excel文件上传失败:" + res.data.errorMsg);
      }
      this.submitForm={
        accountName:''
      }
      //关闭上传弹出层
      this.isVisible_upload = false;
      //清空抽屉文件集合
      this.fileList = [];
      this.excelFile = {};
      this.btnLoading = false;
      this.btnDisabled = false;

    },

    // 上传前校验
    beforeUpload(file) {
      // 文件大小校验（500KB）
      const isLt500KB = file.size / 1024 / 1024 < 0.5;
      if (!isLt500KB) {
        this.$message.error('文件大小不能超过 500KB!');
      }
// 文件类型校验
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('只能上传 .xls 或 .xlsx 格式的文件');
      }
      return isExcel && isLt500KB; // 返回值决定是否继续上传
    },

    // 删除文件时的回调
    handleRemove(file, fileList) {
      console.log('删除文件:', file);
      console.log('文件列表:', fileList);
    },

    // 预览文件时的回调
    handlePreview(file) {
      console.log('预览文件:', file);
    },

    // 上传成功回调
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      console.log('文件:', file);
      console.log('文件列表:', fileList);
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
      this.excelFile=file;
    },
    // 上传失败回调
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      console.log('文件:', file);
      console.log('文件列表:', fileList);
    },
    /**
     * 加载黑名单表格的前置条件
     */
    async downExcel() {
      if (this.total > 0) {
        const res = await this.$confirm(
            "此操作将会把查询出的所有黑名单数据导出, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消导出"
          });
        });
        if (res === "confirm") {
          this.downExcelAll()
        }
      }else {
        this.$message({
          title:'操作失败',
          message:"没有任何数据可导出",
        });
      }
    },
    /**
     * 加载黑名单表格
     */
    downExcelAll() {
      const $this = this;
      const res =   axios.post(
          'http://47.99.186.44:8990/system/blacklist/excel',
          this.queryMap, // 这里需要注意，queryMap 如果是用于请求体，就直接作为第二个参数传入
          {
            responseType: 'blob',
            headers: {
              'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)
            }
          }
      )
          .then(res => {
            if (res.headers["content-type"] === "application/json") {
              return $this.$message.error(
                  "Subject does not have permission [class:export]"
              );
            }
            const data = res.data;
            let url = window.URL.createObjectURL(data); // 将二进制文件转化为可访问的url
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = "黑名单列表.xls";
            a.click();
            window.URL.revokeObjectURL(url);
          });
    },
    downloadTemplate() {
            const $this = this;
            const res = axios.request({
              url: "http://47.99.186.44:8990/template/download",
              method: "post",
              responseType: "blob",
              headers: {
                'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)
              },
              data: {
                templateId: "file:/www/wwwroot/danebCRM/backEnd/client/static/blacklist.xlsx"
              }
            })
                .then(res => {
                  if (res.headers["content-type"] === "application/json") {
                    return $this.$message.error(
                        "Subject does not have permission [class:export]"
                    );
                  }
                  const data = res.data;
                  let url = window.URL.createObjectURL(data);
                  const a = document.createElement("a");
                  document.body.appendChild(a);
                  a.href = url;
                  a.download = "黑名单模版.xlsx";
                  a.click();
                  window.URL.revokeObjectURL(url);
                })
                .catch(error => {
                  console.error("下载出现错误：", error);
                  this.$message.error("文件下载失败，请稍后再试");
                });
    },
    /**
     * 导航栏点击方法
     * @param key 点击下标
     */
    handleSelect(key) {
    },
    /**
     * 重置
     */
    reset(){
      this.value2=[]
      this.queryMap= {
        pageNum: 1,
        pageSize: 10,
        title: "",
        noticeContent: "",
        accountName:'',
      };
      this.getUserName();
    },
    /**
     * 全选功能
     *
     */
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /**
     * 当时间选择时，直接赋值
     */
    handleDateChange() {
      this.queryMap.createTime=this.formatDate(this.value2[0],false);
      this.queryMap.deadline=this.formatDate(this.value2[1],true);
    },
    /**
     * 搜索黑名单
     */
    searchBlackList() {
      this.queryMap.pageNum = 1;
      this.getBlackList();
    },
    /**
     *  改变页码
     */
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getBlackList();
    },
    /**
     * 翻页
     */
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getBlackList();
    },
    //得到黑名单集合
    async getBlackList() {
      const { data: res } = await this.$http.get("/system/blacklist/findList", {
        params: this.queryMap
      });
      if(!res.success){
        return this.$message.error("获取黑名单列表失败:"+res.data.errorMsg);
      }
      this.total = res.data.total;
      this.testData=res.data.rows;
    },
    /**
     * 添加黑名单
     */
    async saveBlacklist(){

      // 验证客户名称是否为空
      if (!this.addForm.accountName) {
        this.$message({
          type: "error",
          message: "账号没有选择"
        });
        return;
      }
      // 验证客户名称是否为空
      if (!this.addForm.clientName) {
        this.$message({
          type: "error",
          message: "客户名称不能为空"
        });
        return;
      }
      // 验证客户电话是否为空
      if (!this.addForm.clientPhone) {
        this.$message({
          type: "error",
          message: "客户电话不能为空"
        });
        return;
      }
      this.btnLoading = true;
      this.btnDisabled = true;
      const { data: res } = await this.$http.post("/system/blacklist/add", this.addForm);
      if(res.success){
        this.$notify.success({
          title:'操作成功',
          message:'黑名单添加成功',
        });
        this.isVisible_add=false
        this.addForm = {};
        await this.getBlackList();
      } else {
        return this.$message.error("黑名单添加失败:" + res.data.errorMsg);
      }
      this.btnLoading = false;
      this.btnDisabled = false;
    },
    /**
     * 清空黑名单
     */
    async del(){
      if (this.total>0){
        const res = await this.$confirm(
            "此操作将会把查询出的所有黑名单移除, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
        if (res === "confirm") {
          const { data: res } = await this.$http.post("/system/blacklist/deletes",this.queryMap);
          console.log(res);
          if(res.success){
            this.$notify.success({
              title:'操作成功',
              message:"查询出的所有黑名单已成功移除",
            });
            await this.getBlackList();
          }else {
            this.$message.error(res.data.errorMsg);
          }
        }
      }else {
        this.$message({
          title:'操作失败',
          message:"没有任何数据可清空",
        });
      }
    },
    /**
     * 批量删除黑名单
     */
    delBlackList(){
      const ids = this.multipleSelection.map(row => row.blacklistId);
      if (ids.length>0) {
        this.delBlack(ids);
      }else {
        this.$message({
          title:'操作失败',
          message:"未选中黑名单",
        });
      }
    },
    /**
     * 删除黑名单
     */
    async delBlack(id) {
      console.log(id)
      const res = await this.$confirm(
          id.length>1?"此操作将会把选中的黑名单移除, 是否继续?":"此操作将会把此黑名单移除, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
      if (res === "confirm") {
        const { data: res } = await this.$http.delete("/system/blacklist/delete/" + id);
        console.log(res);
        if(res.success){
          this.$notify.success({
            title:'操作成功',
            message:id.length>1?"选中的黑名单已成功移除":"此黑名单成功移除",
          });
          await this.getBlackList();
        }else {
          this.$message.error(res.data.errorMsg);
        }
      }
    },
    /**
     * 获得归属人信息
     */
    async getUserName(){
      this.userList=[];
      this.queryMap.userId="";
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/",this.queryMap);
      if(!res.success){
        return this.$message.error("获取归属人信息失败:"+res.data.errorMsg);
      }
      this.userList=res.data
    },
    // 定义一个格式化时间的函数
    formatDate(date,is) {
      //判断时间是否为空
      if (date!=null){
        //判断是否为结束时间
        if (is){
          date.setDate(date.getDate() + 1);
        }
        const year = date.getFullYear();
        //+1，是因为月份是从0开始
        const month = ('0' + (date.getMonth()+1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        // console.log('格式化前各部分值: 年:', year,'月:', month,'日:', day);
        const hours = ('0' + date.getHours()).slice(-2);
        const minutes = ('0' + date.getMinutes()).slice(-2);
        const seconds = ('0' + date.getSeconds()).slice(-2);
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // console.log('最终返回结果:', result);
      }
      return null;
    },
    /**
     * 获得账号信息
     */
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data.errorMsg);
      }
      this.accountName = res.data

    },
  },
  created() {
    this.getAccountNameList();
    this.getBlackList();
    this.getUserName();
  }
};
</script>

<style scoped>
.hint{
  margin-left: 2vh;font-weight: 400;font-size: 12px;color: red;
}
.dataDict{
  border: none;
  background-color: #fff;
  position: absolute;
  padding: .6vh 0;
  font-size: 18px;
}
.popups{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}
.popups .el-main{
  background-color: #fff;
  margin: 15vh auto;
}
.popups .el-main .header{
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}
.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}
</style>
